import  request  from '@/utils/request'
import {defineStore} from 'pinia'
import {categoryItem, IApiRes, TopCategory} from '@/types/data'

import {topCategory} from '../constants'
// 将topCategory中的常量数组转换为对象类型，因为list类型是对象
const topCategoryList = topCategory.map(it => ({id: it, name: it}))

export default defineStore('category', {
  state() {
    return {
      list: topCategoryList as categoryItem[], //分类导航数据
      topCategory: {} as TopCategory
    }
  },
  actions: {
    // 头部分类导航-发请求获取数据
    async getCategoryList() {
      const res = await request.get<IApiRes<categoryItem[]>>('/home/category/head')
      // console.log(res)
      this.list = res.data.result
    },
    // 获取一级类目的数据
    async getTopCategory(id: string) {
      const res = await request.get<IApiRes<TopCategory>>('/category', {
        params: {
          id,
        },
      })
      // console.log(res)
      this.topCategory = res.data.result
    }
  },
  // 持久化保存-插件
  persist: {
    enabled: true
    // key: ''
  }
})

